package com.bee.beemanage.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bee.beemanage.api.entity.SysMenu;
import com.bee.beemanage.api.entity.SysUser;
import com.bee.beemanage.api.entity.output.DepartmentTree;
import com.bee.beemanage.api.entity.output.MenuTree;
import com.bee.beemanage.api.entity.output.UserDetail;
import com.bee.beemanage.api.service.SysDepartmentService;
import com.bee.beemanage.api.service.SysMenuService;
import com.bee.beemanage.api.service.SysUserService;
import com.bee.beemanage.system.common.utils.context.CurrentUser;
import com.bee.beemanage.system.common.utils.pages.PageUtils;
import com.bee.beemanage.system.common.utils.result.Result;
import com.bee.beemanage.system.common.utils.result.ResultCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import static com.bee.beemanage.system.common.utils.result.ResultTool.fail;
import static com.bee.beemanage.system.common.utils.result.ResultTool.success;



@RestController
@RequestMapping("/bee-manage/sys-user")
@Api(value ="用户表",tags = "用户表")
public class SysUserController {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysMenuService sysMenuService;
    @Resource
    private SysDepartmentService sysDepartmentService;
    @Resource
    private PasswordEncoder passwordEncoder;

    @Value("${bee.userDefaultPassword}")
    private String userDefaultPassword;

    /**
    * 新增用户表
    * @param sysUser 用户实体
    * @return 保存是否成功
    */
    @ApiOperation(value = "新增用户表", notes = "新增用户表")
    @PostMapping
    @PreAuthorize("hasAnyAuthority('sys:user:save')")
    public Result save(@RequestBody SysUser sysUser) {
        Result result;
        SysUser userByUserName = sysUserService.findUserByUserName(sysUser.getUsername());
        if(null!=userByUserName){
            result = fail(ResultCode.DATA_REPEAT);
            result.setErrorMsg("已存在用户名为"+sysUser.getUsername()+"的用户");
            return result;
        }
        SysUser loginUser = CurrentUser.getLoginUser();
        sysUser.setCreateTime(LocalDateTime.now());
        sysUser.setCreateUserId(loginUser.getId());
        sysUser.setCreateUserName(loginUser.getUsername());
        sysUser.setPassword(passwordEncoder.encode(userDefaultPassword));
        if(null==sysUser.getAvatar()){
            sysUser.setAvatar("https://manong-authority.oss-cn-guangzhou.aliyuncs.com/avatar/default-avatar.gif");
        }
        return success(sysUserService.save(sysUser));
    }
    /**
    * 修改用户表
    * @param sysUser 用户实体
    * @return 用户编辑是否成功
    */
    @ApiOperation(value = "修改用户表", notes = "修改用户表")
    @PostMapping("/edit")
    @PreAuthorize("hasAnyAuthority('sys:user:edit')")
    public Result edit(@RequestBody SysUser sysUser) {
        Result result = success();
        SysUser loginUser = CurrentUser.getLoginUser();
        sysUser.setUpdateTime(LocalDateTime.now());
        sysUser.setUpdateUserId(loginUser.getId());
        sysUser.setUpdateUserName(loginUser.getUsername());
        if(!sysUserService.updateById(sysUser)){
            result = fail(ResultCode.EDIT_FAIL);
        }
        return result;
    }
    /**
     * 修改密码
     * @param password 新的密码
     * @return 用户修改是否成功
     */
    @ApiOperation(value = "修改密码", notes = "修改密码")
    @PostMapping("/changePassword")
    @PreAuthorize("hasAnyAuthority('sys:user:changePassword')")
    public Result changePassword(@RequestParam String password) {
        Result result = success();
        SysUser loginUser = CurrentUser.getLoginUser();
        SysUser user = sysUserService.findUserByUserName(loginUser.getUsername());
        user.setUpdateTime(LocalDateTime.now());
        user.setUpdateUserId(loginUser.getId());
        user.setUpdateUserName(loginUser.getUsername());
        user.setPassword(passwordEncoder.encode(password));
        if(!sysUserService.updateById(user)){
            result = fail(ResultCode.EDIT_FAIL);
        }
        return result;
    }
    /**
    * 根据id删除用户表
    * @param id 用户id
    * @return 删除结果
    */
    @ApiOperation(value = "通过id删除用户表", notes = "通过id删除用户表")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAnyAuthority('sys:user:removeById')")
    public Result removeById(@PathVariable String id) {
        return success(sysUserService.removeById(id));
    }
    /**
    * 根据id批量删除用户表
    * @param ids 用户id数组
    * @return 删除是否成功
    */
    @ApiOperation(value = "通过id批量删除用户表", notes = "通过id批量删除用户表")
    @PostMapping("/batch")
    @PreAuthorize("hasAnyAuthority('sys:user:removeByIds')")
    public Result removeByIds(@RequestBody String[] ids) {
    List<String> idsList = Arrays.asList(ids);
        return success(sysUserService.removeByIds(idsList));
    }
    /**
     * 数据瘦身，物理删除所有逻辑删除的数据（真删）
     * @return 删除是否成功
     */
    @ApiOperation(value = "物理删除所有逻辑删除的数据", notes = "物理删除所有逻辑删除的数据")
    @DeleteMapping("/clear")
    @PreAuthorize("hasAnyAuthority('sys:user:clear')")
    public Result clear() {
        return success(sysUserService.clear());
    }
    /**
     * 根据id恢复逻辑删除的数据
     * @return 恢复是否成功
     */
    @ApiOperation(value = "根据id恢复逻辑删除的数据", notes = "根据id恢复逻辑删除的数据")
    @PostMapping("/recover")
    @PreAuthorize("hasAnyAuthority('sys:user:recover')")
    public Result recover(@RequestBody String[] ids) {
        List<String> idsList = Arrays.asList(ids);
        return success(sysUserService.recover(idsList));
    }

    /**
     * 用户表分页查询
     *
     * @param current     当前页
     * @param size        一页的条数
     * @param orderColumn 排序字段
     * @param orderAsc    升降序
     * @param sysUser     查询对象
     * @param startTime 创建起始时间
     * @param endTime 创建终止时间
     * @return 带分页信息的用户列表
     */
    @ApiOperation(value = "用户表分页查询", notes = "用户表分页查询")
    @GetMapping("/page")
    @PreAuthorize("hasAnyAuthority('sys:user:page')")
    public Result page(@RequestParam(defaultValue = "0") long current, @RequestParam(defaultValue = "10") long size,
                       String orderColumn, Boolean orderAsc,SysUser sysUser,
                       @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
                       @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        Result result;
        Page<SysUser> page = new Page<>();
        PageUtils.start(current, size, orderColumn, orderAsc, page);
        if (sysUser.getDeleted()) {
            result = success(sysUserService.recycleSearch(page, sysUser, startTime, endTime));
        } else {
            QueryWrapper<SysUser> query = Wrappers.query(sysUser);
            if (null != startTime && null != endTime) {
                query.between("create_time", startTime, endTime);
            }
            result = success(sysUserService.page(page, query));
        }
        return result;
    }

    /**
    * 根据id查询用户表
    * @param id 用户id
    * @return 用户信息
    */
    @ApiOperation(value = "通过id查询用户表", notes = "通过id查询用户表")
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyAuthority('sys:user:getById')")
    public Result getById(@PathVariable("id") String id) {
        return success(sysUserService.getById(id));
    }
    /**
     * 根据Token获取用户信息
     * @return 用户信息和用户菜单树
     */
    @ApiOperation(value = "根据Token获取用户信息", notes = "根据Token获取用户信息")
    @GetMapping("/getUserInfo")
    public Result getUserInfo() {
        UserDetail userDetail = new UserDetail();
        SysUser loginUser = CurrentUser.getLoginUser();
        //获取菜单树
        List<MenuTree> menuTrees = sysMenuService.selectMenuTreeByUserId(loginUser.getId(),null);
        userDetail.setSysUser(loginUser);
        userDetail.setMenuTrees(menuTrees);
        return success(userDetail);
    }

    /**
     *  根据Token获取用户拥有的按钮权限
     * @return 用户拥有的按钮权限
     */
    @ApiOperation(value = "根据Token获取用户拥有的按钮权限", notes = "根据Token获取用户拥有的按钮权限")
    @GetMapping("/getMenuButton")
    public Result getMenuButton() {
        SysUser loginUser = CurrentUser.getLoginUser();
        HashMap<String, Boolean> buttonRole = new HashMap<String, Boolean>();
        List<SysMenu> sysMenus = sysMenuService.selectMenuButtonByUserId(loginUser.getId());
        for (SysMenu sysMenu : sysMenus) {
            if(null!=sysMenu.getButtonCode()){
                buttonRole.put(sysMenu.getButtonCode(),true);
            }
        }
        return success(buttonRole);
    }

    /**
     *  根据Token获取用户拥有的部门树
     * @return 用户拥有的部门树
     */
    @ApiOperation(value = "根据Token获取用户拥有的部门树", notes = "根据Token获取用户拥有的部门树")
    @GetMapping("/getDepartmentTree")
    public Result getDepartmentTree() {
        SysUser loginUser = CurrentUser.getLoginUser();
        List<DepartmentTree> departmentTrees = sysDepartmentService.selectDepartmentTreeByDepartmentId(loginUser.getDepartmentId());
        return success(departmentTrees);
    }
}